/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ManageBean;

import LinkImageBN.InsertimginDB;
import entity.LinkImage;
import java.awt.Image;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author Tulip
 */

@ManagedBean
@SessionScoped
public class UploadPicture implements Serializable {
private List<LinkImage> photos;

    public UploadPicture(){
        photos = new ArrayList<LinkImage>();
    }
    public List<LinkImage> getPhotos() {
        return photos;
    }

    public void handleFileUpload(FileUploadEvent event) {
        FileOutputStream outStream = null;
        try {
            ExternalContext exContext = FacesContext.getCurrentInstance().getExternalContext();
            String fileName = event.getFile().getFileName();
            String ext = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + ext;
            String realFolder = exContext.getRealPath("/images/");
            File file = new File(realFolder);
            if (!file.exists()) {
                file.mkdirs();
            }
            outStream = new FileOutputStream(realFolder + "/" + newFileName);
            outStream.write(event.getFile().getContents());
            entity.LinkImage photo = new entity.LinkImage();
            photo.setLinkImageHouse("/images/" + newFileName);
            photos.add(photo);
//            InsertimginDB ins = new InsertimginDB();
//            String someaccount = "someaccount";
//            ins.insertimg(photos, someaccount);
//            SellerMB smb = new SellerMB();
//            smb.setPhotos(photos);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                outStream.close();
            } catch (IOException ex) {
                Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private void clear() {
        photos = new ArrayList<entity.LinkImage>();
    }
}
